import { notification } from 'antd';
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { createHashHistory } from 'history';
import { getToken, removeToken } from './auth';

const isQianKun = window.__POWERED_BY_QIANKUN__; // 当前是否为乾坤环境
const history = createHashHistory();

// 接口定义返回的数据 返回的数据 多一项或少一项都将报错
declare interface responseData<T> {
  code: number;
  msg: string;
  data: T;
}
// window.config.baseURL
const BASE_URL =
  process.env.NODE_ENV === 'development' ? '/api' : window.config.baseUrl;

const instance = axios.create({
  baseURL: BASE_URL,
  withCredentials: true,
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    // console.log('token', token);

    if (token) {
      config.headers = {
        ...config.headers,
        Authorization: token,
      };
    }
    // debugger
    return config;
  },
  (error) => {
    console.log('请求拦截器报错', error);
    return Promise.resolve(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    const res = response.data as responseData<any>;
    // 返回200正常返回
    if (res.code === 200) {
      return res || true;
    }
    if (res.code === 403) {
      history.replace('/403');
      return;
    }
    // 登录失效
    if (res.code === 401) {
      removeToken();
      history.replace('/login');
      return;
    }
    if (res.code === 500) {
      // 弹出错误信息
      // router.push({ name: '500', params: { message: res.msg || '出现错误' } });
      return;
    }
    if (res.code === 501) {
      return res || true;
    }
  },
  (error) => {
    // console.log('响应拦截器', error);
    notification.open({
      message: 'Tips',
      description: error + '',
    });
  }
);

// 设置请求方法
// 有待考虑的错版方法
const requset = <T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<T> => {
  if (typeof config === 'string') {
    if (!options) {
      return instance.request<T, T>({
        url: config,
      });
    } else {
      return instance.request<T, T>({
        url: config,
        ...options,
      });
    }
  } else {
    return instance.request<T, T>(config);
  }
};

export function get<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<responseData<T>> {
  return requset<responseData<T>>({ ...config, method: 'GET' }, options);
}

export function post<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<responseData<T>> {
  return requset<responseData<T>>({ ...config, method: 'POST' }, options);
}

export function put<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<responseData<T>> {
  return requset<responseData<T>>({ ...config, method: 'PUT' }, options);
}

export function del<T = any>(
  config: AxiosRequestConfig,
  options?: AxiosRequestConfig
): Promise<responseData<T>> {
  return requset<responseData<T>>({ ...config, method: 'DELETE' }, options);
}

export default requset;
export type { AxiosInstance, AxiosResponse };
